package com.qingzhuge.resource.dao;


import com.qingzhuge.common.enums.EResourceType;
import com.qingzhuge.dao.BasePkLongDao;
import com.qingzhuge.resource.entity.SysResource;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @author : zero.xiao
 * @description : 菜单管理
 * @date :2018/6/8 0008 下午 14:53
 * @modified :
 */
public interface SysResourceDao extends BasePkLongDao<SysResource> {

    /**
     * 根据父菜单，查询子菜单
     *
     * @param parent 父菜单
     */
    List<SysResource> queryByParentOrderByOrderNumAsc(SysResource parent);

    /**
     * 查询所有根菜单
     * @return 根菜单
     */
    List<SysResource> queryByParentIsNullOrderByOrderNumAsc();

    @Query(nativeQuery = true, value = "select distinct rm.resource_id from sys_user_role ur \n" +
            " LEFT JOIN sys_role_resource rm on ur.role_id = rm.role_id\n" +
            " where ur.user_id = ?1")
    List<SysResource> queryByUserId(Long uid);


    @Query(nativeQuery = true, value = "select DISTINCT resource.permission permission\n" +
            "from sys_resource resource \n" +
            "join sys_user_resource um on um.resource_id=resource.id\n" +
            "where length(resource.permission)>0 and um.user_id=?1 and resource.permission is not null\n" +
            "union\n" +
            "select DISTINCT resource.permission permission\n" +
            "from sys_resource resource \n" +
            "join sys_role_resource rm on rm.resource_id=resource.id\n" +
            "join sys_user_role ur on ur.role_id=rm.role_id\n" +
            "where length(resource.permission)>0 and ur.user_id=?1  and resource.permission is not null")
    List<String> queryPermissionByUserId(Long uid);

    @Query(nativeQuery = true, value = "select DISTINCT resource.permission permission\n" +
            "from sys_resource resource \n" +
            "join sys_user_resource um on um.resource_id=resource.id\n" +
            "where length(resource.permission)>0 and um.user_id=?1 and resource.permission is not null\n" +
            "union\n" +
            "select DISTINCT resource.permission permission\n" +
            "from sys_resource resource \n" +
            "join sys_role_resource rm on rm.resource_id=resource.id\n" +
            "where length(resource.permission)>0 and rm.role_id=?1  and resource.permission is not null")
    List<String> queryPermissionByRoleId(Long roled);

    @Query(value = "from SysResource resource where resource.type <> ?1")
    List<SysResource> queryByTypeButtonNot(EResourceType type);

    SysResource findByUrlAndRequestMethod(String url, String requestMethod);

    SysResource findByNameAndType(String name, EResourceType type);
}
